#include "snakegame.h"

#include "snake.h"

#include <QDebug>

Game::Game()
{ ; }

void Game::setup(QString p, int cl, int gx, int gy)
{
    player = p;
    date = QDate::currentDate();
    cellLenght = cl;
    grid_x = gx;
    grid_y = gy;
}

void Game::start()
{
    scores = 0;
    level = 1;
    int h = int(grid_y/2);
    QVector<QPoint> snake_body;
    snake_body.append( QPoint(3,                    3 + h*(cellLenght+1)) );
    snake_body.append( QPoint(3 + (cellLenght+1),   3 + h*(cellLenght+1)) );
    snake_body.append( QPoint(3 + 2*(cellLenght+1), 3 + h*(cellLenght+1)) );
    wall = QRect(1, 1, grid_x*(cellLenght+1) + 2, grid_y*(cellLenght+1) + 2);
    snake = new Snake(wall, cellLenght);
    snake->born(snake_body);
}

void Game::setData(QString p, int l, int s, QDate d)
{
    player = p;
    level = l;
    scores  = s;
    date = d;
    qDebug() << "setting date: " << date.toString("dd/MM/yyyy");
}

void Game::restartGame(int l, int s, QVector<QPoint> b, QPoint e)
{
    level = l;
    scores = s;
    wall = QRect(1, 1, grid_x*(cellLenght+1) + 2, grid_y*(cellLenght+1) + 2);
    snake = new Snake(wall, cellLenght);
    snake->born(b);
    eat = e;
}

QRect Game::getWall()
{
    return wall;
}

int Game::getLevel()
{
    return level;
}


int Game::getScores()
{
    return scores;
}

QString Game::getPlayer()
{
    qDebug() << "Game name: "<< player;
    return player;
}

QDate Game::getDate()
{
    return date;
}

Snake * Game::getSnake()
{
    return snake;
}

QVector<QPoint> & Game::getSnakeBody()
{
    return snake->getBody();
}

QPoint Game::getSnakeHead()
{
    return snake->getHead();
}

QPoint Game::createEat()
{
    int  x, y;
    bool valid = false;
    while (!valid){
        x = 3 + (cellLenght+1)*int( float(grid_x) * rand() / float(RAND_MAX) );
        y = 3 + (cellLenght+1)*int( float(grid_y) * rand() / float(RAND_MAX) );
        eat = QPoint(x, y);
        valid = snake->isValidEat(eat);
    }
    return eat;
}

QPoint Game::getEat()
{
    return eat;
}

void Game::save(FILE *arq)
{
    fprintf(arq,"%s\n", player.toStdString().data());
    QString s;
    s.append(date.toString("dd/MM/yyyy"));
    fprintf(arq,"%s\n", s.toStdString().data());
    fprintf(arq,"%i\n", level);
    fprintf(arq,"%i\n", scores);
    fprintf(arq,"%i %i\n", eat.x(), eat.y()); // eat position x y
    QVector<QPoint>& body = snake->getBody();
    fprintf(arq,"%i\n", body.size());
    for(int i=0; i<body.size(); i++){
        fprintf(arq,"%i %i\n", body[i].x(), body[i].y());
    }
}
